package thingapi

import (
	"iot-base/common/dbconn"
	"iot-base/common/webapi"
	"strings"

	"github.com/gin-gonic/gin"
)

const sqlQueryBase = `select thing1.s_name,thing1.uid,ts.station_id,thing2.s_name as station_name,tm.s_name as model_name,
thing1.model_id as model_id,thing_params.param_value as ip
from thing_stations ts,things thing2,t_models tm,things thing1`
const sqlJoin = ` left join thing_params on thing1.uid = thing_params.thing_id and lower(thing_params.param_id) = 'ip' `

const sqlWhere = ` where 
ts.thing_id = thing1.uid and 
thing2.uid = ts.station_id and 
thing1.model_id = tm.uid and
thing1.is_station = false`

func initThingQueryAPI(router *gin.RouterGroup) {
	queryAPI := router.Group("/thingQuery")
	{
		queryAPI.GET("/thingAll/", func(c *gin.Context) {
			res, err := query()
			webapi.SendResult(res, err, c)

		})
		queryAPI.GET("/thing", func(c *gin.Context) {
			conditon := c.Query("condition")
			res, err := queryByCondition(conditon)
			webapi.SendResult(res, err, c)

		})
		queryAPI.GET("/thing/online/", func(c *gin.Context) {
			result, err := queryByOnlineState("=1")
			webapi.SendResult(result, err, c)
		})

		queryAPI.GET("/cfg", func(c *gin.Context) {
			res := GetThingsAllCfg()
			webapi.SendResult(res, nil, c)
		})

	}

}
func query() ([]map[string]interface{}, error) {
	var things []map[string]interface{}
	err := dbconn.DBConnection.Table("things").
		Joins("left join thing_states on thing_states.thing_id = things.uid").
		Joins("left join t_models on t_models.uid = things.model_id").
		Joins("left join stations on stations.uid = things.uid").
		Joins("left join thing_stations on thing_stations.thing_id = things.uid").
		Select(`things.*,t_models.s_name as model_name,thing_states.state,stations.parent_id,
		thing_stations.station_id,t_models.catalog_id as catalog_id`).Find(&things).Error

	return things, err
}

func queryByCondition(condition string) ([]map[string]interface{}, error) {
	sql := sqlQueryBase + sqlJoin + sqlWhere + ` and (
	LOWER(thing1.s_name) like '%condition%' or 
	LOWER(thing1.uid) like '%condition%' or 
	LOWER(thing1.business_id) like '%condition%' or
	LOWER(tm.s_name) like '%condition%'
	or thing_params.param_value like '%condition%')`
	sql = strings.ReplaceAll(sql, "%condition%", "%"+condition+"%")
	var things []map[string]interface{}
	err := dbconn.DBConnection.Raw(sql).Find(&things).Error
	return things, err
}

func queryByOnlineState(state string) (interface{}, error) {
	sql := sqlQueryBase + ",thing_states tsts " +
		" join thing_params on tsts.thing_id = thing_params.thing_id and lower(thing_params.param_id) = 'ip'  " +
		sqlWhere + " and tsts.thing_id=thing1.uid and tsts.state " + state
	var result []map[string]interface{}
	err := dbconn.DBConnection.Raw(sql, state).Find(&result).Error
	return result, err
}
